// funcs
package jkutils

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
	"strings"
)

func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

func PKCS7UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	return origData[:(length - unpadding)]
}

//AES加密
func AesEncrypt(origData, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS7Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
	crypted := make([]byte, len(origData))
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

//AES解密
func AesDecrypt(crypted, key []byte) ([]byte, error) {
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
	origData := make([]byte, len(crypted))
	blockMode.CryptBlocks(origData, crypted)
	origData = PKCS7UnPadding(origData)
	return origData, nil
}
func EncBinStr(buf []byte) string {
	s := ""
	for _, b := range buf {
		s += fmt.Sprintf("%08b", b)
	}
	return s
}

//简单加密算法，str明文，返回hex编码密文
func SimpleEncrypt(str string) string {
	o := []byte(str)
	d := make([]byte, len(o))
	for i, b := range o {
		d[i] = b ^ 0xA5
	}
	return hex.EncodeToString(d)
}

//简单解密算法，str为hex编码密码，返回解密后的明文
func SimpleDecrypt(str string) (string, error) {
	o, e := hex.DecodeString(str)
	if e != nil {
		return "", e
	}
	d := make([]byte, len(o))
	for i, b := range o {
		d[i] = b ^ 0xA5
	}
	return string(d), nil
}

func EqualIgnorecase(s1, s2 string) bool {
	s1 = strings.ToLower(s1)
	s2 = strings.ToLower(s2)
	return s1 == s2
}
